class WS {
	constructor() {
		this.ws    = null;
		this.timer = null;
		this.data  = [];
	}

	init(opts) {
		this.ping      = opts.ping    || null;
		this.methods   = opts.methods || {};
		this.onopen    = opts.onopen  || new Function('');
		this.onerror   = opts.onerror || new Function('');
		this.onclose   = opts.onclose || new Function('');
		this.onmessage = opts.onmessage;
	}

	connect(url) {
		const self = this;
		self.ws = new WebSocket(url);

		// 监听连接
		self.ws.onopen = () => {
			(typeof self.ping == 'number') && self.runPing();
			self.onopen();
		};

		// 监听错误
		self.ws.onerror = self.onerror;

		// 监听断开
		self.ws.onclose = () => {
			clearTimeout(self.timer);
			self.timer = null;
			self.onclose();
		};

		// 监听 - 消息
		if (typeof self.onmessage == 'function') {
			self.ws.onmessage = self.onmessage;
		} else {
			self.ws.onmessage = opts => {
				let data = {};
				try {
					data = JSON.parse(opts.data);
				} catch (e) {
					//TODO handle the exception
					data = {};
				}
				self.methods[data.type] && self.methods[data.type](data.data);
				// 数据存储
				data.type && (self.data[data.type] = data.data || '');
			};
		}
	}

	// -------------------------------------

	// 发送消息
	send(opts) {
		// console.log("发送传递数据：",opts)
		let data = (typeof opts == 'string' || typeof opts == 'number') ? opts : JSON.stringify(opts);
		this.ws.send(data);
	}

	// 关闭连接
	close() {
		const self = this;
		self.ws && self.ws.close();
	}

	// -------------------------------------

	// 心跳包
	runPing(times) {
		const self = this;
		clearTimeout(self.timer);
		self.timer = null;
		loop();

		function loop() {
			self.timer = setTimeout(() => {
				if (self.timer == null) return;
				// console.log("%c"+">>> ping","color:green");
				self.ws.send(JSON.stringify({
					type: 'ping'
				}));
				loop();
			}, self.ping * 1000);
		}
	}
};